package com.fesine.hibernate.service;

import com.fesine.hibernate.model.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

/**
 * Created by Fesine on 2016/5/21.
 */
public class StudentService {

    //测试hibernate
    public static void main(String[] args) {
        // 1、实例化配置文件 使用hibernate的配置类
        Configuration configuration = new Configuration().configure();
        // 2、实例化服务登记
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();
        // 3、获取session工厂
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        // 4、创建session
        Session session = sessionFactory.openSession();
        // 5、开启事务
        session.beginTransaction();
        /** 操作数据库开始 */
        Student student = new Student();
        student.setName("fesine");
        session.save(student);
        /** 操作数据库结束 */
        // 提交事务
        session.getTransaction().commit();
        //最后关闭事务
        session.close();
        //关闭工厂
        sessionFactory.close();

    }
}
